/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.wangxiandeng.swipecardrecyclerview.adapter;

import com.wangxiandeng.swipecardrecyclerview.ResourceTable;
import ohos.agp.components.*;
import ohos.app.Context;

import java.lang.reflect.Array;
import java.util.ArrayList;

/**
 * provider
 */
public class BaseAdapter extends BaseItemProvider {
  private Context mContext;

  private ArrayList<String> mDataList;

  /**
   * constructor
   *
   * @param context context
   */
  public BaseAdapter(Context context) {
    mContext = context;
  }

  /**
   * set data in the list
   *
   * @param dataList data source
   */
  public void setData(ArrayList<String> dataList) {
    this.mDataList = dataList;
    super.notifyDataChanged();
  }

  @Override
  public int getCount() {
    return mDataList == null ? 0 : mDataList.size();
  }

  @Override
  public String getItem(int position) {
    return mDataList.get(position);
  }

  @Override
  public long getItemId(int position) {
    return position;
  }

  @Override
  public Component getComponent(int position, Component convertView, ComponentContainer container) {
    MyComponentHolder holder;
    if (convertView == null) {
      convertView = LayoutScatter.getInstance(mContext).parse(ResourceTable.Layout_item,
          container, false);
      holder = new MyComponentHolder(convertView);
      convertView.setTag(holder);
    } else {
      holder = (MyComponentHolder) convertView.getTag();
    }
    Text text = (Text) holder.getItemView().findComponentById(ResourceTable.Id_helloText);
//        text.setText(mDataList.get(position));
    text.setText(mDataList.get(position));
    return convertView;
  }

  /**
   * item component holder
   */
  public static class MyComponentHolder {
    private final Component itemView;

    public MyComponentHolder(Component itemView) {
      if (itemView == null) {
        throw new IllegalArgumentException("itemView may not be null");
      } else {
        this.itemView = itemView;
      }
    }

    public Component getItemView() {
      return itemView;
    }
  }
}
